package com.lunago.agent.service.impl;

import com.lunago.agent.pojo.entity.ChatRecord;
import com.lunago.agent.service.ChatRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class ChatRecordServiceImpl implements ChatRecordService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, String content, String owner) {
        ChatRecord chatRecord = new ChatRecord();
        chatRecord.setUserId(userId);
        chatRecord.setContent(content);
        chatRecord.setOwner(owner);
        chatRecord.setCreatedAt(System.currentTimeMillis());
        mongoTemplate.save(chatRecord, "chat_record");
    }

    @Override
    public List<ChatRecord> queryAllLimit(Long userId, int limit) {
        // 构造查询条件
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        // 按 createdAt 倒序排序
        query.with(Sort.by(Sort.Order.desc("createdAt")));
        if (limit > 0) {
            query.limit(limit);
        }
        // 执行查询
        return mongoTemplate.find(query, ChatRecord.class, "chat_record");
    }
}
